package com.wsp.controllermanagement.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.wsp.controllermanagement.security.AdminRealm;
import com.wsp.controllermanagement.security.SecurityMatcher;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Package: com.wsp.controllermanagement.config
 * Description： TODO
 *
 * @Author: 巫思平
 * Copyright: Copyright (c) 2020
 * Version: 1
 */
@Configuration
public class ShrioConfig {
    @Autowired
    private SecurityMatcher matcher;

    /**
     * 身份认证 Realm
     */
    @Bean("adminRealm")
    public AdminRealm adminRealm(){
        AdminRealm adminRealm = new AdminRealm();
        adminRealm.setAuthenticationTokenClass(AuthenticationToken.class);
        adminRealm.setCredentialsMatcher(matcher);
        return adminRealm;
    }

    /**
     * 安全管理器
     */
    @Bean("defaultWebSecurityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        defaultWebSecurityManager.setRealm(adminRealm());
        return defaultWebSecurityManager;
    }

    /**
     * 过滤器工厂（配置过滤规则）
     */
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(getDefaultWebSecurityManager());
        //添加shiro的内置过滤器
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/swagger**/**","anon");
        filterMap.put("/v3/**","anon");
        filterMap.put("/doc.html","anon");
        filterMap.put("/admin/login","anon");
        filterMap.put("/admin/test","anon");
        filterMap.put("/admin/addAdmin","authc");
        //权限拦截
        filterMap.put("/admin/**","authc");
        bean.setFilterChainDefinitionMap(filterMap);
        bean.setLoginUrl("/toLogin");
        return bean;
    }


    /**
     * thymeleaf整合shiro
     */
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
